package k2kra;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.*;

public class Client {

	public static final String SERVER_IP = "172.81.216.162";
	public static final int SERVER_PORT = 5000;

	public static Vector<String> resp = new Vector<String>();

	public static void main(String[] args) throws IOException {
		// 172.81.216.162
		Socket sock = new Socket(SERVER_IP, SERVER_PORT);
		try (InputStream input = sock.getInputStream()) {
			try (OutputStream output = sock.getOutputStream()) {
				handler(input, output);
			}
		}
		sock.close();
		System.out.println("disconnected.");
	}

	private static void handler(InputStream input, OutputStream output) throws IOException {
		var writer = new BufferedWriter(new OutputStreamWriter(output, StandardCharsets.UTF_8));
		var reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8));
		Scanner scanner = new Scanner(System.in);
		new Thread(new Runnable() {

			@Override
			public void run() {
				while (true) {
					String s;
					try {
						s = reader.readLine();
						resp.add(s);
					} catch (IOException e) {
						e.printStackTrace();
						System.out.println("failed to connect server.");
						System.exit(0);
					}
				}
			}
		}).start();
		while ( true ) {

			//等待
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

			//读取服务器消息
			while (!resp.isEmpty()) {
				System.out.println(resp.remove(resp.size() - 1));
			}

			//读取用户输入
			System.out.print("[you]");
			String s = scanner.nextLine();
			if (s == null) return;
			if (!s.equals("")) {
				writer.write(s);
				writer.newLine();
				writer.flush();
			}
		}
	}

}
